package com.example.springframeworklearning.converter;

import com.example.springframeworklearning.domain.Order;
import com.example.springframeworklearning.domain.OrderItem;
import com.example.springframeworklearning.enums.OrderStatus;
import com.example.springframeworklearning.propertyeditor.LocalDateTimePropertyEditor;
import com.example.springframeworklearning.propertyeditor.OrderItemListPropertyEditor;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.PropertyEditorRegistrar;
import org.springframework.core.convert.converter.Converter;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;

/**
 * 自定义的将 hashMap 转换为 Order 的 转换器
 * @author luo
 * @since 2022/9/20 13:09
 */
public class MapToOrderConverter implements Converter<Map<String, Object>, Order> {



    @Override
    public Order convert(Map<String, Object> source) {

        Order result = new Order();

        Object createTime = source.get("createTime");
        if (createTime != null) {

            result.setCreateTime(
                    LocalDateTime.of(
                            LocalDate.parse(createTime.toString(), DateTimeFormatter.ofPattern("yyyyMMdd")),
                            LocalTime.MIN
                    )
            );
        }
        Object orderStatus = source.get("orderStatus");
        if(orderStatus!=null){

            result.setOrderStatus(
                    new StringOrderStatusConverterFactory.StringToEnumConverter<OrderStatus>().convert(orderStatus.toString())
            );
        }

        BeanWrapperImpl beanWrapper = new BeanWrapperImpl(result);
        beanWrapper.registerCustomEditor(OrderItem.class,new  OrderItemListPropertyEditor());
        beanWrapper.setPropertyValue("orderItemList",source.get("orderItemList"));
        return (Order) beanWrapper.getWrappedInstance();
    }
}
